﻿using System;

namespace _2._两数相加
{
    /// <summary>
    /// https://leetcode.cn/problems/add-two-numbers/
    /// </summary>
    public class Solution
    {
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            ListNode nodeStart = new ListNode(0, null);
            ListNode node = nodeStart;

            int carryBit = 0;
            while (l1 != null || l2 != null || carryBit != 0)
            {
                var y = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carryBit;//二数之和 加  进位

                node.next = new ListNode(y % 10);

                carryBit = y / 10 ;

                l1 = l1!=null?l1.next:l1;
                l2 = l2!=null?l2.next:l2;

                node = node.next;

            }

            return nodeStart.next;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ListNode node1 = new ListNode(2, new ListNode(4, new ListNode(9)));
            ListNode node2 = new ListNode(5, new ListNode(6, new ListNode(4)));
            ListNode node = new Solution().AddTwoNumbers(node1, node2);

            Print(node1);
            Console.WriteLine();
            Print(node2);
            Console.WriteLine();
            Print(node);
        }

        static void Print(ListNode n)
        {
            if (n.next == null)
            {
                Console.Write(n.val);
                return;
            }
            Print(n.next);

            Console.Write(n.val);
        }
    }


    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int val = 0, ListNode next = null)
        {
            this.val = val;
            this.next = next;
        }
    }
}
